package com.blog.controller.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.blog.pojo.MLogin;
import com.blog.util.CookieUtil;
import com.blog.util.JsonUtil;
import com.blog.util.RedisPoolUtil;

public class LoginInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		
		//MLogin user = (MLogin)request.getSession().getAttribute("user");
		
		//redis 方式
		MLogin user = null;
		String cookie = CookieUtil.readLoginToken(request);
		 
		//如果cookie不为空,从redis中取得用户
		if(StringUtils.isNotEmpty(cookie)){
			String userStr = RedisPoolUtil.get(cookie);
			user = JsonUtil.string2Obj(userStr, MLogin.class);
			//System.out.println(user.toString());
		} 
		
		if(user == null){
			
			//未登录
			
			request.setAttribute("msg", "没有权限，请先登录");
			request.getRequestDispatcher("/login").forward(request, response);
			return false;
		}else{
			//已登录,放行
			
			return true;
		}
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
